package com.innerchic.weqiuqiu.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.UiModeManager;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Parcelable;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.app.RemoteInput;

import com.google.gson.Gson;
import com.innerchic.mapper.log.Logger;
import com.innerchic.mapper.tool.MD5;
import com.innerchic.sponsor.Sponsor;
import com.innerchic.weqiuqiu.bean.MessageBean;
import com.innerchic.weqiuqiu.bean.MessageRemove;
import com.innerchic.weqiuqiu.bean.MessageReply;
import com.innerchic.weqiuqiu.bean.ServiceStatus;

import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：wedudu
 * 日    期：2022/1/14 10:35
 * 包    名：com.innerchic.weqiuqiu.service
 * 描    述：通知消息服务
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */
public class MessageCoreService extends NotificationListenerService {

    private static boolean startService = false;

    public static boolean isStartService() {
        return startService;
    }

    @Override
    public void onListenerConnected() {
        super.onListenerConnected();
        startService = true;
        //发送通知
        ServiceStatus serviceStatus = new ServiceStatus();
        serviceStatus.setServiceIsOpen(true);
        Sponsor.getDefault().post(serviceStatus);
        Logger.d("MessageCoreService.onListenerConnected()服务启动...");
    }

    @Override
    public void onListenerDisconnected() {
        super.onListenerDisconnected();
        startService = false;
        //发送通知
        ServiceStatus serviceStatus = new ServiceStatus();
        serviceStatus.setServiceIsOpen(false);
        Sponsor.getDefault().post(serviceStatus);
        Logger.d("MessageCoreService.onListenerDisconnected()服务关闭...");
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        super.onNotificationPosted(sbn);
        //检查是否开启了功能
        boolean is_open_qiuqiu = getSharedPreferences("system_config_all", 0).getBoolean("is_open_qiuqiu", false);
        if (!is_open_qiuqiu) {
            return;
        }

        //解析包名
        String packageName = sbn.getPackageName();
        boolean isPackageNameLegal = isThePackageNameLegal(packageName);
        if (!isPackageNameLegal) {
            return;
        }

        //解析消息体
        Notification notification = sbn.getNotification();
        Bundle extras = notification.extras;
        String title = extras.getString(Notification.EXTRA_TITLE);
        String content = extras.getString(Notification.EXTRA_TEXT);
        int smallIconId = extras.getInt(Notification.EXTRA_SMALL_ICON);
        //头像可能是Bitmap类型也可能是Icon类型
        Parcelable parcelable = extras.getParcelable(Notification.EXTRA_LARGE_ICON);
        //空的通知过滤掉
        if (title == null || parcelable == null) {
            return;
        }

        Log.d("NotificationPackageName", "onNotificationPosted: " + packageName + " ,[Title]" + title + " ,[Content]" + content);

        //系统发出的不拦截
        if ("android".equals(packageName)) {
            return;
        }

        //初始化消息列表
        MessageReply messageEcho = null;
        MessageBean bean = new MessageBean();
        bean.setType(2);
        bean.setSmallIconId(smallIconId);
        bean.setMessageSource(packageName);
        bean.setParcelable(parcelable);

        //md5Key值
        String as = packageName + "," + title + "," + content;
        String encrypt = MD5.encrypt(as);
        bean.setMd5Key(encrypt);

        //设置启动项
        PendingIntent openPendingIntent = sbn.getNotification().contentIntent;
        bean.setOpenPendingIntent(openPendingIntent);

        //检查微信的消息回复体
        if ("com.tencent.mm".equals(packageName)) {
            openDriveModel();
            //获取回复项
            messageEcho = getMessageEcho(notification);
            bean.setMessageReply(messageEcho);
            //设置发送者名称
            bean.setName(title);
            //解析条数
            Pattern compile = Pattern.compile("\\[.{1,2}?条]");
            Matcher matcher = compile.matcher(content);
            boolean hasArticle = matcher.find();
            String message = content;
            if (hasArticle) {
                String articleText = matcher.group();
                message = message.replace(articleText, "");
                String number = articleText.substring(articleText.indexOf("[") + 1, articleText.indexOf("条"));
                try {
                    int anInt = Integer.parseInt(number);
                    bean.setCount(anInt);
                } catch (Exception e) {
                    bean.setCount(0);
                }
            } else {
                bean.setCount(0);
            }
            bean.setContent(message);
            //解析消息体
            if (message.contains(" ")) {
                //有人at你
                bean.setType(1);
                bean.setAtYou(true);
                message = message.substring(message.indexOf(" ") + 1);
            }
            //截取一下"昵称:"
            String titleA = bean.getName() + ": ";
            if (message.startsWith(titleA)) {
                message = message.replace(titleA, "");
            }
            bean.setMessage(message);

//            if ("[微信红包]".equals(message)) {
//                //红包消息
//                boolean wechat_red_package_remind = getSharedPreferences("function_wechat_status", 0)
//                        .getBoolean("wechat_red_package_remind", false);
//                if (wechat_red_package_remind) {
//                    //发送
//                    Sponsor.getDefault().post(bean);
//                }
//            }
        } else if ("com.tencent.mobileqq".equals(packageName)) {
            bean.setMessage(content);
            bean.setContent(content);
            bean.setName(title);
            if (content.contains("[有人@我]")) {
                bean.setType(1);
                bean.setAtYou(true);
            }
            //解析条数
            Pattern compile = Pattern.compile("\\(.{1,3}?条新消息\\)");
            Matcher matcher = compile.matcher(title);
            boolean hasArticle = matcher.find();
            if (hasArticle) {
                String articleText = matcher.group();
                bean.setName(title.replace(articleText, ""));
                String number = articleText.substring(articleText.indexOf("(") + 1, articleText.indexOf("条新消息)"));
                try {
                    int anInt = Integer.parseInt(number);
                    bean.setCount(anInt);
                } catch (Exception e) {
                    bean.setCount(0);
                }
            } else {
                bean.setCount(0);
            }
        } else if ("com.alibaba.android.rimet".equals(packageName)) {
            bean.setName(title);
            bean.setMessage(content);
            bean.setContent(content);
        } else {
            int regular_cleaning_paopao_timer = getSharedPreferences("function_other_status", 0)
                    .getInt("regular_cleaning_paopao_timer", 2);
            bean.setCloseTime(regular_cleaning_paopao_timer * 1000L);
            bean.setName(title);
            bean.setMessage(content);
            bean.setContent(content);
        }
        //发送
        Sponsor.getDefault().post(bean);
    }

    /**
     * 获取消息回传器
     * //微信接收消息类:com.tencent.mm.plugin.auto.service.MMAutoMessageReplyReceiver
     */
    private MessageReply getMessageEcho(Notification notification) {
        NotificationCompat.CarExtender carExtender = new NotificationCompat.CarExtender(notification);
        NotificationCompat.CarExtender.UnreadConversation unreadConversation = carExtender.getUnreadConversation();
        if (unreadConversation != null) {
            PendingIntent replyPendingIntent = unreadConversation.getReplyPendingIntent();
            RemoteInput remoteInput = unreadConversation.getRemoteInput();
            //key_voice_reply_text
            String key = remoteInput.getResultKey();
            if (replyPendingIntent != null) {
                MessageReply messageReply = new MessageReply();
                messageReply.setKey(key);
                messageReply.setReplyPendingIntent(replyPendingIntent);
                return messageReply;
            } else {
                Logger.d("回传结果集为null.");
            }
        } else {
            Logger.d("NotificationCompat.CarExtender.UnreadConversation值为null.");
        }
        return null;
    }

    /**
     * 判断包名是否合法需要解析
     *
     * @return true需要
     */
    private boolean isThePackageNameLegal(String packageName) {
        SharedPreferences function_status = getSharedPreferences("function_status", 0);
        if ("com.tencent.mm".equals(packageName)) {
            return function_status.getBoolean("wechat_status", true);
        } else if ("com.tencent.mobileqq".equals(packageName)) {
            return function_status.getBoolean("qq_status", false);
        } else if ("com.alibaba.android.rimet".equals(packageName)) {
            return function_status.getBoolean("dingding_status", false);
        } else {
            return function_status.getBoolean("other_status", false);
        }
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        super.onNotificationRemoved(sbn);
        String packageName = sbn.getPackageName();
        //解析消息体
        Notification notification = sbn.getNotification();
        Bundle extras = notification.extras;
        String title = extras.getString(Notification.EXTRA_TITLE);
        String content = extras.getString(Notification.EXTRA_TEXT);
        //空的通知过滤掉
        if (title == null || content == null) {
            return;
        }
        Log.d("NotificationPackageName", "onNotificationRemoved: " + packageName + " ,[Title]" + title + " ,[Content]" + content);
        if ("com.tencent.mm".equals(packageName) || "com.tencent.mobileqq".equals(packageName) || "com.alibaba.android.rimet".equals(packageName)) {
            return;
        }
        //回传被移除
        String as = packageName + "," + title + "," + content;
        String encrypt = MD5.encrypt(as);
        Sponsor.getDefault().post(new MessageRemove(encrypt));
    }

    /**
     * 判断是否开启了驾车模式
     */
    @SuppressLint("WrongConstant")
    private void openDriveModel() {
        boolean isOpenCarMode = ((UiModeManager) getSystemService("uimode")).getCurrentModeType() == Configuration.UI_MODE_TYPE_CAR;
        if (!isOpenCarMode) {
            UiModeManager uimode = (UiModeManager) getSystemService("uimode");
            uimode.enableCarMode(0);
        }
    }

}
